package org.dragonnova.iot.business.cloud.transport.model;

/**
 * * 请求包帧头格式： 
 * ****************************** * 
 * ** phone 8 byte  (电话号码) 
 * * data 通信数据
 */

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import org.dragonnova.iot.business.cloud.transport.ParseException;
import org.dragonnova.iot.business.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description: 数据通信
 * @company winter
 */
public class DataCommPacket extends NPacket {
	// 默认通信功能码
	public static final byte DATACOMM_TYPE_CODE_UNSUPPORTED_OPERATION = (byte) 0x09;
	// 通信包回传功能码
	public static final byte DATACOMM_TYPE_CODE_ACK = (byte) 0x85;
	// 数据通信校验码
	public static final byte DATACOMM_TYPE_CODE_CHECK = (byte) 0x10;

	private final static Logger LOGGER = LoggerFactory
			.getLogger(AckPacket.class);

	private long phone;
	private byte[] data;

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		this.data = data;
	}

	public long getPhone() {
		return phone;
	}

	public void setPhone(long phone) {
		this.phone = phone;
	}

	public DataCommPacket() {
		this(DATACOMM_TYPE_CODE_UNSUPPORTED_OPERATION, DATACOMM_TYPE_CODE_CHECK);
	}

	public DataCommPacket(byte code, byte checkCode) {
		this.mt = code;
		this.checkCode = checkCode;
	}

	public byte getMtCode() {
		return this.mt;
	}

	@Override
	protected void decodeBody(ByteBuf byteBuf) {
		try {
			phone = byteBuf.readLong();
			data = new byte[this.bodyLength - Long.BYTES];
			byteBuf.readBytes(data);
			this.setSize((short) (this.bodyLength + 8));
			this.checkCode = byteBuf.readByte();
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("DataCommPacket Code: [\'"
						+ Utils.printHexString(this.mt) + "\'] Packet.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected ByteBuf encodeBody() {
		try {
			this.bodyLength = (short) (data.length + Long.BYTES);
			final ByteBuf buffer = Unpooled.directBuffer(this.PACK_PUBLIC_LEN
					+ bodyLength);
			buffer.writeByte(Packet.HEADER);
			buffer.writeByte(this.mt);
			buffer.writeBytes(Utils
					.int2HLbyte((short) (this.PACK_PUBLIC_LEN + bodyLength)));
			buffer.writeBytes(Utils.long2HLByte(phone, Long.BYTES));
			buffer.writeBytes(data);// 数据
			buffer.writeByte(this.checkCode);// 校验
			buffer.writeBytes(Packet.END);
			return buffer;
		} catch (Exception e) {
			throw new ParseException("DataCommPacket encode error: caused by "
					+ e.getMessage());
		}
	}

	@Override
	protected void releasePacket() {
		// TODO Auto-generated method stub
	}
}
